﻿using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using AuthenticationAPI.Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using AuthenticationAPI.Models.DbContext;
using System.Collections.Generic;
using AuthenticationAPI.Models.Utility;
namespace AuthenticationAPI.Controllers
{

    public class AuthorizeController : ApiController
    {


        [Route("api/UserNameOccupied/{userName}")]
        [HttpGet]
        public HttpResponseMessage UserNameOccupied(string userName = "")
        {
            using (var db = new AuthenticationEntities())
            {
                var nameCandidate = db.Candidate.SingleOrDefault(p => p.UserName == userName);
                var nameUser = db.User.SingleOrDefault(p => p.UserName == userName);
                var occupy = nameCandidate == null && nameUser == null ? false : true;
                return Request.CreateResponse(HttpStatusCode.OK, occupy);
            }
        }

        [Route("api/wechatexist/{wechatId}")]
        [HttpGet]
        public HttpResponseMessage WechatExist(string wechatId)
        {
            using (var db = new AuthenticationEntities())
            {
                var user = db.User.FirstOrDefault(t => t.WechatId == wechatId);
                var exist = user == null ? 0 : 1;
                return Request.CreateResponse(HttpStatusCode.OK, exist);
            }
        }


        [Route("api/login")]
        [HttpPost]
        public HttpResponseMessage LogIn([FromBody]string jsonStr)
        {
            using (var db = new AuthenticationEntities())
            {
                var logInfo = JsonConvert.DeserializeObject<loginUser>(jsonStr);
                var tempUser = db.User.SingleOrDefault(p => p.UserName.ToLower() == logInfo.userName.Trim().ToLower());
                if (tempUser == null || tempUser.Password != logInfo.password || tempUser.Freeze == 1)
                {
                    //登录不成功
                    return Request.CreateResponse(HttpStatusCode.Forbidden, "Access Denied!");
                }
                else
                {
                    //默认给一个头像
                    tempUser.Avatar = string.IsNullOrEmpty(tempUser.Avatar) ? UserHelper.avatarGenerator() : tempUser.Avatar;
                    if (logInfo.wechatId != null && logInfo.wechatId != "")
                    {
                        tempUser.WechatId = logInfo.wechatId;
                    }
                    db.SaveChanges();
                    return Request.CreateResponse(HttpStatusCode.OK,
                        AuthenticationAPI.Models.Utility.UserHelper.GetUserInfo(tempUser));
                }
            }
        }


        [Route("api/test/{p1}/{p2}")]
        [HttpGet]
        public string Test(string p1, string p2)
        {
            var userInfo = new userInfo()
            {
                phone = "123",
                userName = "wangji",
                password = "dfffasfa"
            };
            var jStr = JsonConvert.SerializeObject(userInfo);
            var User = JsonConvert.DeserializeObject<User>(jStr);

            return JsonConvert.SerializeObject(User);
        }

        /// <summary>
        /// 申请一个账号
        /// </summary>
        /// <param name="jsonStr"></param>
        /// <returns></returns>
        [Route("api/applyaccount")]
        [HttpPost]
        public HttpResponseMessage ApplyAccount([FromBody]string jsonStr)
        {
            var candidateInfo = JsonConvert.DeserializeObject<Applier>(jsonStr);
            using (var db = new AuthenticationEntities())
            {
                //一开始用户填入的reviewer 是真名,在数据库操作后,要把reviewer替换成用户名
                var rewiewerFull = db.User.
                    SingleOrDefault(p => p.RealName == candidateInfo.Reviewer
                        && p.Corporation == candidateInfo.Corporation);

                var rewiewer = new Applier()
                             {
                                 RealName = rewiewerFull.RealName,
                                 UserName = rewiewerFull.UserName,
                                 Phone = rewiewerFull.Phone,
                                 Mail = rewiewerFull.Mail
                             };

                //替换成reviewer的用户名
                candidateInfo.Reviewer = rewiewerFull.UserName;
                var candidate = new Candidate()
                {
                    Mail = candidateInfo.Mail,
                    Password = candidateInfo.Password,
                    Phone = candidateInfo.Phone,
                    RealName = candidateInfo.RealName,
                    Reviewer = candidateInfo.Reviewer,
                    UserName = candidateInfo.UserName
                };
                db.Candidate.Add(candidate);
                db.SaveChanges();

                return Request.CreateResponse(HttpStatusCode.OK, rewiewer);
            }

        }




        ///// <summary>
        ///// 获取管理员,temp
        ///// </summary>
        ///// <returns></returns>
        //[Route("api/reviewers")]
        //[HttpGet]
        //public HttpResponseMessage GetReviewers()
        //{
        //    using (var db = new AuthenticationEntities())
        //    {
        //        var corporations = (from p in db.User
        //                            where p.Authentication == "CorpAdministrator" ||
        //                                p.Authentication == "DepartAdministrator"
        //                            group p by p.Corporation into g
        //                            select new corporation()
        //                            {
        //                                admins = g.Select(t => t.RealName).ToList(),
        //                                name = g.Key,
        //                            }).ToList();

        //        return Request.CreateResponse(HttpStatusCode.OK, corporations);

        //    }
        //}


    }
}
